<?php

/**
 * @see module_base
 */
class module_testing extends module_base
{
    function get_questions_array($test)
    {
        $questions_array = array();
        $themes = get_themes_for_test_id($test->id);

        // Get all questions for themes.
        for ($i = 0; $i < count($themes); $i++)
        {
            $questions_array[$i] = array();
            $theme = $themes[$i];
            $questions = get_questions_for_theme_id($theme['theme_id']);
            foreach($questions as $question)
            {
                $questions_array[$i][] = $question;
            }
        }

        for ($i = 0; $i < count($themes); $i++)
        {
            $theme = $themes[$i];
            $questions_count = count($questions_array[$i]);
            if ($test->is_exam_mode == 1)
            {
                for ($j = 0; $j < $questions_count; $j++)
                {
                    $tmp_index = rand(0, $questions_count-1);
                    $tmp = $questions_array[$i][$j];
                    $questions_array[$i][$j] = $questions_array[$i][$tmp_index];
                    $questions_array[$i][$tmp_index] = $tmp;
                }
            }
            if ($test->is_exam_mode == 0)
            {
                $count = get_questions_count_for_theme_id($theme['theme_id']);
            }
            else
            {
                $count = $theme['theme_numexam'];
            }

            $questions_array[$i] = array_slice($questions_array[$i], 0, $count);
        }

        $questions = array();
        for ($i = 0; $i < count($themes); $i++)
        {
            foreach($questions_array[$i] as $question)
            {
                $questions[] = $question;
            }
        }

        if (($test->is_sort_by_theme == 0) && ($test->is_exam_mode == 1))
        {
            $questions_count = count($questions);

            for ($j = 0; $j < $questions_count; $j++)
            {
                $tmp_index = rand(0, $questions_count-1);
                $tmp = $questions[$j];
                $questions[$j] = $questions[$tmp_index];
                $questions[$tmp_index] = $tmp;
            }
        }

        /* Sort by question number. */
        if (($test->is_sort_by_theme == 0) && ($test->is_exam_mode == 0))
        {
            $array = array();
            $questions_count = count($questions);
            for ($j = 0; $j < $questions_count; $j++)
            {
                $array[$questions[$j]['question_number']] = $questions[$j];
            }

            ksort($array);
            $questions = $array;
        }

        /* Get question id array */
        $array = array();
        foreach($questions as $question)
        {
            $array[] = $question['question_id'];
        }
        return $array;
    }

    function get_answers_for_questions_array($test, $questions_array)
    {
        $answers_array = array();
        foreach($questions_array as $question)
        {
            $answers = get_answers_for_question_id($question);
            $answers_array[$question] = array();

            $answers_count = count($answers);
            for ($i = 0; $i < $answers_count; $i++)
            {
                $answer = $answers[$i];
                $answers_array[$question][$i] = $answer['answer_id'];
            }
            if ($test->is_random_answers == 1)
            {
                $question_class = get_question($question);
                if ($question_class->type == 3)
                {
                    $answers_count = count($answers)/2;
                }
                else
                {
                    $answers_count = count($answers);
                }
                for ($j = 0; $j < $answers_count; $j++)
                {
                    $tmp_index = rand(0, $answers_count-1);
                    $tmp = $answers_array[$question][$j];
                    $answers_array[$question][$j] = $answers_array[$question][$tmp_index];
                    $answers_array[$question][$tmp_index] = $tmp;
                }
            }
        }

        return $answers_array;
    }

    function get_correct_answer_question_type_0($question, $answers)
    {
        $answer_text = '';

        foreach($answers as $answer)
        {
            if (isset($answer['answer_right']) &&
                ($answer['answer_right'] == 1)
               )
            {
                $answer_text = $answer['answer_text_html'];
                break;
            }
        }

        return $answer_text;
    }

    function get_correct_answer_question_type_1($question, $answers)
    {
        $items = array();

        foreach($answers as $answer)
        {
            if (isset($answer['answer_right']) &&
                ($answer['answer_right'] == 1)
               )
            {
                $items[] = $answer['answer_text_html'];
            }
        }

        return implode("\n", $items);
    }

    function get_correct_answer_question_type_2($question, $answers)
    {
        return (isset($question->etalon) ? $question->etalon : '');
    }

    function get_correct_answer_question_type_3($question, $answers)
    {
        $items = array();
        foreach($answers as $answer)
        {
            $tmp = $answer['answer_corresp'] - 1;
            if ($tmp != -1)
            {
                $items[] = $answer['answer_text'].' - '.$answers[$tmp]['answer_text_html'];
            }
        }

        return implode("\n", $items);
    }

    function get_correct_answer_question_type_4($question, $answers)
    {
        $items = array();
        foreach($answers as $answer)
        {
            $tmp = $answer['answer_corresp'] - 1;
            $items[$tmp] = $answer['answer_text_html'];
        }
        ksort($items);

        return implode("\n", $items);
    }

    function get_correct_answer($question, $answers)
    {
        switch($question->type)
        {
            case 0:
                $answer = $this->get_correct_answer_question_type_0($question, $answers);
                break;

            case 1:
                $answer = $this->get_correct_answer_question_type_1($question, $answers);
                break;

            case 2:
                $answer = $this->get_correct_answer_question_type_2($question, $answers);
                break;

            case 3:
                $answer = $this->get_correct_answer_question_type_3($question, $answers);
                break;

            case 4:
                $answer = $this->get_correct_answer_question_type_4($question, $answers);
                break;

            default:
                $answer = '';
        }

        return $answer;
    }

    function get_time_left()
    {
        if (!isset($_SESSION['test']['user_result_id']))
        {
            return NULL;
        }
        $user_result_id = $_SESSION['test']['user_result_id'];
        $time = get_user_result_test_time($user_result_id);

        list($h, $m, $s) = preg_split('/:/', $_SESSION['test']['time_limit']);
        $time_limit = $h*60*60 + $m*60 + $s;
        $time_left = $time_limit - $time;
        if ($time_left <= 0)
        {
            return NULL;
        }

        return gmdate('H:i:s', $time_left);
    }

    private function section_form()
    {
        global $WEB_APP;

        $WEB_APP['scripts'][] = 'change_section.js';
        $WEB_APP['scripts'][] = 'get_test_description.js';

        $user_id = get_user_id($_SESSION['user_login']);
        $sections = get_unhidden_sections_for_user_id($user_id);
        $tests = array();
        $section = '';
        $test = '';

        if (count($_POST) > 0)
        {
            if (isset($_POST['section_id']) && is_scalar($_POST['section_id']))
            {
                $tmp = get_section($_POST['section_id']);
                if (isset($tmp->id))
                {
                    $section = $tmp->name;
                    $tests = get_unhidden_tests_for_section_id($tmp->id);
                }
            }
        }

        $fields[] = new field(TRUE, text('txt_section'), 'select',
                    'section_id', $section, '', $sections,
                    'id', 'section_name', 'return change_section()', FALSE);
        $fields[] = new field(TRUE, text('txt_test'), 'select', 'test_id',
                    $test, '', $tests, 'id', 'test_name', 'return get_test_description()', TRUE);

        $WEB_APP['fields'] = $fields;
        $WEB_APP['description_field'] = 'test_description';
        $WEB_APP['title'] = text('txt_testing');
        $WEB_APP['form_title'] = text('txt_change');
        $WEB_APP['submit_title'] = text('txt_choose');
        $WEB_APP['view']->display('form_page.tpl', text('txt_testing'));
    }

    private function all_tests_form()
    {
        global $WEB_APP;

        $WEB_APP['scripts'][] = 'get_test_description.js';

        $user_id = get_user_id($_SESSION['user_login']);
        $tests = get_tests_for_user_id($user_id);
        $test = '';

        $fields[] = new field(TRUE, text('txt_test'), 'select', 'test_id',
                    $test, '', $tests, 'id', 'test_name', 'return get_test_description()', TRUE);

        $WEB_APP['fields'] = $fields;
        $WEB_APP['description_field'] = 'test_description';
        $WEB_APP['title'] = text('txt_testing');
        $WEB_APP['form_title'] = text('txt_change');
        $WEB_APP['submit_title'] = text('txt_choose');
        $WEB_APP['view']->display('form_page.tpl', text('txt_testing'));

    }

    private function new_test()
    {
        global $WEB_APP;

        $WEB_APP['scripts'][] = 'jquery.js';

        unset($_SESSION['test']['test_id']);
        unset($_SESSION['test']['current_question']);
        unset($_SESSION['test']['previous_question']);
        unset($_SESSION['test']['previous_answer']);
        unset($_SESSION['test']['questions']);

        $tst_test_selection_style = $WEB_APP['settings']['tst_test_selection_style'];

        if ($tst_test_selection_style == TEST_SELECT_TEST_FROM_SECTION)
        {
            $this->section_form();
        }
        else
        {
            $this->all_tests_form();
        }

        exit();
    }

    function change_section()
    {
        global $WEB_APP;

        $tst_test_selection_style = $WEB_APP['settings']['tst_test_selection_style'];

        if ($tst_test_selection_style != TEST_SELECT_TEST_FROM_SECTION)
        {
            die();
        }

        if (isset($_GET['section_id']) && is_scalar($_GET['section_id']))
        {
            $section_id = (int) $_GET['section_id'];
        }
        else
        {
            die();
        }

        $section = get_section($section_id);
        if (!isset($section->id))
        {
            die();
        }
        if ($section->hidden)
        {
            die();
        }

        $tests = get_unhidden_tests_for_section_id($section->id);
        echo "<option selected=\"\" value=\"\"></option>\n";
        foreach($tests as $test)
        {
            printf("<option value=\"%d\">%s</option>\n", $test['id'], htmlspecialchars($test['test_name']));
        }
        die();
    }

    function get_test_description()
    {
        global $WEB_APP;

        if (isset($_GET['test_id']) && is_scalar($_GET['test_id']))
        {
            $test_id = (int) $_GET['test_id'];
        }
        else
        {
            die();
        }

        $test = get_test($test_id);
        if (!isset($test->id))
        {
            die();
        }
        // Check is test enable for current user.
        $result = FALSE;
        $user_id = get_user_id($_SESSION['user_login']);
        $tests = get_tests_for_user_id($user_id);

        foreach($tests as $tmp)
        {
            $result = ($result || ($tmp['id'] == $test_id));
        }

        if ($result)
        {
            echo $test->description;
        }
        die();
    }

    function unset_test()
    {
        unset($_SESSION['errorstext']);
        unset($_SESSION['correct_answer_message']);
        unset($_SESSION['test']);
    }

    function is_select_test()
    {
        return (
                (!isset($_SESSION['test']['test_id'])) &&
                (isset($_POST['test_id']) || isset($_POST['section_id']) || isset($_GET['tid']) || isset($_GET['tname']))
               );
    }

    function check_new_test_id($test_id)
    {
        global $WEB_APP;

        $user_id = get_user_id($_SESSION['user_login']);
        $test = get_test($test_id);

        if (!isset($test->id))
        {
            $WEB_APP['errorstext'] = text('txt_choose_test').'<br>';
            return FALSE;
        }
        # Check is user have access to test.
        $access = FALSE;
        $tests = get_tests_for_user_id($user_id);
        foreach($tests as $tmp)
        {
            $access = $access || ($tmp['id'] == $test_id);
        }

        if ($access === FALSE)
        {
            $WEB_APP['errorstext'] = text('txt_choose_test').'<br>';
            return FALSE;
        }

        # Check is test from section.
        $tst_test_selection_style = $WEB_APP['settings']['tst_test_selection_style'];

        if ($tst_test_selection_style == TEST_SELECT_TEST_FROM_SECTION)
        {
            if (isset($_POST['section_id']) && is_string($_POST['section_id']))
            {
                $section_id = (int) $_POST['section_id'];
                $access = FALSE;
                $tests = get_unhidden_tests_for_section_id($section_id);

                foreach($tests as $tmp)
                {
                    $access = $access || ($tmp['id'] == $test_id);
                }

                if ($access === FALSE)
                {
                    $WEB_APP['errorstext'] = text('txt_choose_test').'<br>';
                    return FALSE;
                }
            }
        }

        $count = get_user_results_count_for_test_id($user_id, $test_id);
        if (($count >= $test->max_count) && ($test->max_count > 0))
        {
            $WEB_APP['errorstext'] .= text('txt_you_exceed_maximal_amount_of_testing_for_this_test').'<br>';
            return FALSE;
        }

        $questions = $this->get_questions_array($test);
        if (count($questions) == 0)
        {
            $WEB_APP['errorstext'] = text('txt_no_questions_choose_another_test').'<br>';
            return FALSE;
        }

        return $test_id;
    }

    function new_test_check_get_params()
    {
        if (isset($_GET['tid']) || isset($_GET['tname']))
        {
            $id = 0;

            if (isset($_GET['tid']) && is_string($_GET['tid']))
            {
                $id = (int) $_GET['tid'];
            }

            if (isset($_GET['tname']) && is_string($_GET['tname']))
            {
                $id = get_test_id_by_name($_GET['tname']);
            }

            return $this->check_new_test_id($id);
        }

        return FALSE;
    }

    function new_test_check_post_params()
    {
        global $WEB_APP;

        if (count($_POST) > 0)
        {
            $id = 0;
            if (isset($_POST['test_id']) && is_string($_POST['test_id']))
            {
                $id = (int) $_POST['test_id'];
            }

            $tst_test_selection_style = $WEB_APP['settings']['tst_test_selection_style'];

            if ($tst_test_selection_style == TEST_SELECT_TEST_FROM_SECTION)
            {
                if (isset($_POST['section_id']) && is_string($_POST['section_id']))
                {
                    $section_id = (int) $_POST['section_id'];

                    $user_id = get_user_id($_SESSION['user_login']);

                    $sections = get_unhidden_sections_for_user_id($user_id);
                    $result = FALSE;

                    foreach($sections as $section)
                    {
                        $result = $result || ($section['id'] == $section_id);
                    }

                    if (!$result)
                    {
                         $WEB_APP['errorstext'] .= text('txt_choose_section').'<BR>';
                         return FALSE;
                    }
                }
                else
                {
                    $WEB_APP['errorstext'] .= text('txt_choose_section').'<BR>';
                    return FALSE;
                }
            }

            return $this->check_new_test_id($id);
        }

        return FALSE;
    }

    function begin_test($test_id)
    {
        global $WEB_APP;

        $user_id = get_user_id($_SESSION['user_login']);
        $test = get_test($test_id);
        $_SESSION['test']['test_id'] = $test_id;

        $questions = $this->get_questions_array($test);
        if (!isset($_SESSION['test']['questions']))
        {
            $_SESSION['test']['questions'] = $questions;
        }

        $answers = $this->get_answers_for_questions_array($test, $questions);
        $_SESSION['test']['results'] = array();
        $_SESSION['test']['score'] = array();
        for($i = 0; $i < count($_SESSION['test']['questions']); $i++)
        {
            $_SESSION['test']['results'][$_SESSION['test']['questions'][$i]] = NULL;
        }

        $_SESSION['test']['answers'] = $answers;
        $_SESSION['test']['time_limit'] = $test->time_limit;
        $_SESSION['test']['start_time'] = time();
        $_SESSION['test']['correct_answers'] = 0;
        $_SESSION['test']['user_result_id'] = add_user_result($user_id, count($questions), $test_id, serialize($_SESSION['test']));
        $_SESSION['test']['current_question'] = 0;
        $_SESSION['test']['all_questions'] = TRUE;

        // Build user_result_themes
        $_SESSION['test']['user_result_themes'] = array();
        $themes = get_themes_for_test_id($test->id);
        foreach($themes as  $theme)
        {
            $_SESSION['test']['user_result_themes'][$theme['theme_id']] = array();
            $_SESSION['test']['user_result_themes'][$theme['theme_id']]['title'] = $theme['theme_caption'];
            $_SESSION['test']['user_result_themes'][$theme['theme_id']]['show_in_results'] = $theme['theme_show_in_results'];
            $_SESSION['test']['user_result_themes'][$theme['theme_id']]['id'] = add_user_result_theme($_SESSION['test']['user_result_id'], $theme['theme_caption'], '');
        }
        header('Location: '.$WEB_APP['cfg_url'].'?module=testing');
        exit();

    }

    function view()
    {
        global $WEB_APP;
        if (isset($_POST['current_question']) &&
            isset($_SESSION['test']) &&
            isset($_SESSION['test']['current_question']) &&
            isset($_SESSION['test']['questions']) &&
            isset($_SESSION['test']['questions'][$_SESSION['test']['current_question']])
           )
        {
            if ($_POST['current_question'] != $_SESSION['test']['questions'][$_SESSION['test']['current_question']])
            {
                header('Location: '.$WEB_APP['cfg_url'].'?module=testing');
                exit();
            }
        }
        $correct_answer = '';
        $user_id = get_user_id($_SESSION['user_login']);
        $tests = get_tests_for_user_id($user_id);

        $fields = array();
        if (isset($_SESSION['test']['test_id']))
        {
            $test = get_test($_SESSION['test']['test_id']);
            if (!isset($test->id))
            {
                $this->unset_test();
            }

            if (!isset($_SESSION['test']['user_result_id']))
            {
                $this->unset_test();
            }
            else
            {
                $user_result = get_user_result($_SESSION['test']['user_result_id']);
                if (!isset($user_result->id))
                {
                    $this->unset_test();
                }
                else
                {
                    if ($user_result->completed)
                    {
                        $this->unset_test();
                    }
                }
            }
        }
        // Проверяем если это get или post запрос выбора теста.
        if ($this->is_select_test())
        {
            $id = $this->new_test_check_post_params();

            if ($id === FALSE)
            {
                $id = $this->new_test_check_get_params();
            }

            if ($id !== FALSE)
            {
                $this->begin_test($id);
            }
        }


        // New test.
        if (!isset($_SESSION['test']['test_id']))
        {
            $this->new_test();
        }

        ########### Update current question to db ####################
        if (isset($_SESSION['test']['current_question']))
        {
            $user_result = get_user_result($_SESSION['test']['user_result_id']);
            $user_result->test_data = serialize($_SESSION['test']);

            edit_user_result($user_result);
        }

        $correct_answer = TRUE;
        $test = get_test($_SESSION['test']['test_id']);
        if ($test->is_time_limit == 1)
        {
            if ($this->get_time_left() == NULL)
            {
                $correct_answer = FALSE;
            }
        }

        //if ($correct_answer)
        if (isset($_POST['submit_button']) && !isset($_POST['answer']))
        {
            $_SESSION['errorstext'] = text('txt_insert_answer').'<BR>';
        }
        if (isset($_POST['submit_button']) && (count($_POST) > 0) && isset($_POST['answer']))
        {
            $this->time();
            $out_time = ($this->get_time_left() == NULL) && ($test->is_time_limit == 1);

            $question = get_question($_SESSION['test']['questions'][$_SESSION['test']['current_question']]);

            $answers = get_answers_for_question_id($question->id);

            if ($out_time)
            {
                $user_answer = new user_answer();
                $user_answer->user_result_id = $_SESSION['test']['user_result_id'];
                $user_answer->qnumber = $question->number;
                $user_answer->question = $question->text_html;
                $user_answer->answer = '';
                $user_answer->time = get_utc_time();
                $user_answer->is_right = 0;
                $user_answer->theme_id = $_SESSION['test']['user_result_themes'][$question->theme_id]['id'];
                $user_answer->correct_answer = $this->get_correct_answer($question, $answers);
                $user_answer->score = 0;
                $answer_text = '';
                if (is_showed_question($_SESSION['test']['user_result_id'], $question->id))
                {
                    edit_user_answer($user_answer);
                }
                else
                {
                    add_user_answer($user_answer);
                }
            }

            if (!$out_time)
            switch($question->type)
            {
                case 0:
                    $answer_number = $_POST['answer'];
                    $_SESSION['test']['results'][$question->id] = $answer_number;
                    $answer = $answers[$answer_number];
                    $correct_answer = ($answer['answer_right'] == 1);
                    $answer_text = $answer['answer_text_html'];
                    $user_answer = new user_answer();
                    $user_answer->user_result_id = $_SESSION['test']['user_result_id'];
                    $user_answer->qnumber = $question->number;
                    $user_answer->question = $question->text_html;
                    $user_answer->answer = $answer['answer_text_html'];
                    $user_answer->time = get_utc_time();
                    $user_answer->is_right = $correct_answer ? 1 : 0;
                    $user_answer->theme_id = $_SESSION['test']['user_result_themes'][$question->theme_id]['id'];
                    $user_answer->correct_answer = $this->get_correct_answer($question, $answers);
                    if ($test->type == TEST_TYPE_SCORED)
                    {
                    	$user_answer->score = $answer['answer_score'];
                    }
                    else
                    {
                        if ($correct_answer)
                    	{
                        	$user_answer->score = ($correct_answer ? $question->weight : 0);
                        }
                        else
                    	{
                        $user_answer->score = 0;
                    	}
                    }

                    $user_answer->answered = (count($_POST['answer']) == 1) ? 1 : 0;
                    $user_answer->question_id = $question->id;

                    if (is_showed_question($_SESSION['test']['user_result_id'], $question->id))
                    {
                        edit_user_answer($user_answer);
                    }
                    else
                    {
                        add_user_answer($user_answer);
                    }
                    break;

                case 1:
                    $answer_numbers = $_POST['answer'];
                    $_SESSION['test']['results'][$question->id] = $answer_numbers;
                    $correct_answer = TRUE;
                    $answer_text = '';
                    $correct_count = 0;
                    if (count($answer_numbers) == 0)
                    {
                        $correct_answer = FALSE;
                    }
                    else
                    {
                        foreach($answer_numbers as $answer_number)
                        {
                            $answer = $answers[$answer_number];
                            $answer_text .= $answer['answer_text_html'];
                            if ($answer['answer_right'] == 1)
                            {
                                $correct_count++;
                            }
                            $correct_answer = $correct_answer && ($answer['answer_right'] == 1);
                        }
                    }
                    $count = 0;

                    foreach($answers as $answer)
                    {
                        if ($answer['answer_right'] == 1)
                        {
                            $count++;
                        }
                    }

                    $correct_answer = $correct_answer && ($count == count($answer_numbers));

                    $user_answer = new user_answer();
                    $user_answer->user_result_id = $_SESSION['test']['user_result_id'];
                    $user_answer->qnumber = $question->number;
                    $user_answer->question = $question->text_html;
                    $user_answer->answer = $answer_text;
                    $user_answer->time = get_utc_time();
                    $user_answer->is_right = $correct_answer ? 1 : 0;
                    $user_answer->theme_id = $_SESSION['test']['user_result_themes'][$question->theme_id]['id'];
                    $user_answer->correct_answer = $this->get_correct_answer($question, $answers);

                    if ($correct_answer)
                    {
                        if ($test->type == TEST_TYPE_COMMON)
                        {
                            $user_answer->score = $question->weight;
                        }

                        if ($test->type == TEST_TYPE_SCORED)
                        {
                            $user_answer->score = 0;
                            foreach($answer_numbers as $answer_number)
                            {
                                $answer = $answers[$answer_number];
                                $user_answer->score += $answer['answer_score'];
                            }
                        }
                    }
                    else
                    {
                        if ($test->type == TEST_TYPE_SCORED)
                        {
                            $user_answer->score = 0;
                            foreach($answer_numbers as $answer_number)
                            {
                                $answer = $answers[$answer_number];
                                $user_answer->score += $answer['answer_score'];
                            }
                        }
                        else
                        {
                            $user_answer->score = 0;
                        }
                    }
                    $user_answer->answered = (count($_POST['answer']) > 0) ? 1 : 0;
                    $user_answer->question_id = $question->id;
                    if (is_showed_question($_SESSION['test']['user_result_id'], $question->id))
                    {
                        edit_user_answer($user_answer);
                    }
                    else
                    {
                        add_user_answer($user_answer);
                    }
                    break;
                case 2:
                    $answer = $_POST['answer'];
                    $answer_text = $answer;
                    $_SESSION['test']['results'][$question->id] = $answer;
                    $etalon = $question->etalon;
                    $is_case_sensetive = $question->is_case_sensetive;
                    if ($WEB_APP['settings']['admset_regexpformat'] == 'POSIX')
                    {
                        if ($question->is_case_sensetive == 1)
                        {
                            $correct_answer = @mb_ereg($etalon, $answer);
                        }
                        else
                        {
                            $correct_answer = @mb_eregi($etalon, $answer);
                        }
                    }
                    else
                    {
                        $correct_answer = @mb_ereg_match($etalon, $answer);
                    }
                    $user_answer = new user_answer();
                    $user_answer->user_result_id = $_SESSION['test']['user_result_id'];
                    $user_answer->qnumber = $question->number;
                    $user_answer->question = $question->text_html;
                    $user_answer->answer = $answer;
                    $user_answer->time = get_utc_time();
                    $user_answer->is_right = $correct_answer ? 1 : 0;

                    $user_answer->score = ($correct_answer ? $question->weight : 0);

                    $user_answer->answered = 1;
                    $user_answer->question_id = $question->id;
                    $user_answer->theme_id = $_SESSION['test']['user_result_themes'][$question->theme_id]['id'];
                    $user_answer->correct_answer = $this->get_correct_answer($question, $answers);
                    if (is_showed_question($_SESSION['test']['user_result_id'], $question->id))
                    {
                        edit_user_answer($user_answer);
                    }
                    else
                    {
                        add_user_answer($user_answer);
                    }
                    break;

                case 3:
                    $answer_numbers = $_POST['answer'];
                    $_SESSION['test']['results'][$question->id] = $answer_numbers;
                    $correct_answer = TRUE;
                    $count = count($answers)/2;
                    $answer_text = '<table>';
                    $correct_count = 0;
                    for ($i = 0; $i < $count; $i++)
                    {
                        if ($answers[$i]['answer_corresp'] == $answer_numbers[$i])
                        {
                            $correct_count++;
                        }
                        $answer_text .= '<tr><td>'.$answers[$i]['answer_text_html'].'</td><td>'.$answers[$answer_numbers[$i]-1]['answer_text_html'].'</td></tr>';
                        $correct_answer = $correct_answer && ($answers[$i]['answer_corresp'] == $answer_numbers[$i]);
                    }
                    $answer_text .= '</table>';

                    $user_answer = new user_answer();
                    $user_answer->user_result_id = $_SESSION['test']['user_result_id'];
                    $user_answer->qnumber = $question->number;
                    $user_answer->question = $question->text_html;
                    $user_answer->answer = $answer_text;
                    $user_answer->time = get_utc_time();
                    $user_answer->is_right = $correct_answer ? 1 : 0;
                    $user_answer->theme_id = $_SESSION['test']['user_result_themes'][$question->theme_id]['id'];
                    $user_answer->correct_answer = $this->get_correct_answer($question, $answers);

                    if ($correct_answer)
                    {
                        if ($test->type == TEST_TYPE_COMMON)
                        {
                            $user_answer->score = $question->weight;
                        }

                        if ($test->type == TEST_TYPE_SCORED)
                        {
                            $user_answer->score = 0;

                            for ($i = 0; $i < $count; $i++)
                            {
                                if ($answers[$i]['answer_corresp'] == $answer_numbers[$i])
                                {
                                    $user_answer->score += $answers[$i]['answer_score'] + $answers[$answers[$i]['answer_corresp'] - 1]['answer_score'];
                                }
                            }
                        }
                    }
                    else
                    {
                        if ($test->type == TEST_TYPE_SCORED)
                        {
                            $user_answer->score = 0;
                            for ($i = 0; $i < $count; $i++)
                            {
                                if ($answers[$i]['answer_corresp'] == $answer_numbers[$i])
                                {
                                    $user_answer->score += $answers[$i]['answer_score'] + $answers[$answers[$i]['answer_corresp'] - 1]['answer_score'];
                                }
                            }
                        }
                        else
                        {
                            $user_answer->score = 0;
                        }
                    }
                    $user_answer->answered = 1;
                    $user_answer->question_id = $question->id;
                    if (is_showed_question($_SESSION['test']['user_result_id'], $question->id))
                    {
                        edit_user_answer($user_answer);
                    }
                    else
                    {
                        add_user_answer($user_answer);
                    }
                    break;

                case 4:
                    $answer_numbers = $_POST['answer'];
                    asort($answer_numbers);
                    $_SESSION['test']['results'][$question->id] = $answer_numbers;
                    $correct_answer = TRUE;
                    $count = count($answers);

                    $answer_text = '<table>';
                    foreach($answer_numbers as $key => $value)
                    {
                        $answer_text .= '<tr><td>'.$answers[$key]['answer_text_html'].'</td></tr>';
                    }

                    $correct_count = 0;

                    for ($i = 0; $i < $count; $i++)
                    {
                        if ($answers[$i]['answer_corresp'] == $answer_numbers[$i])
                        {
                            $correct_count++;
                        }
                        $correct_answer = $correct_answer && ($answers[$i]['answer_corresp'] == $answer_numbers[$i]);
                    }
                    $answer_text .= '</table>';

                    $user_answer = new user_answer();
                    $user_answer->user_result_id = $_SESSION['test']['user_result_id'];
                    $user_answer->qnumber = $question->number;
                    $user_answer->question = $question->text_html;
                    $user_answer->answer = $answer_text;
                    $user_answer->time = get_utc_time();
                    $user_answer->is_right = $correct_answer ? 1 : 0;
                    $user_answer->theme_id = $_SESSION['test']['user_result_themes'][$question->theme_id]['id'];
                    $user_answer->correct_answer = $this->get_correct_answer($question, $answers);

                    if ($correct_answer)
                    {
                        if ($test->type == TEST_TYPE_COMMON)
                        {
                            $user_answer->score = $question->weight;
                        }

                        if ($test->type == TEST_TYPE_SCORED)
                        {
                            $user_answer->score = 0;

                            for ($i = 0; $i < $count; $i++)
                            {
                                if ($answers[$i]['answer_corresp'] == $answer_numbers[$i])
                                {
                                    $user_answer->score += $answers[$i]['answer_score'];
                                }
                            }
                        }
                    }
                    else
                    {
                        if ($test->type == TEST_TYPE_SCORED)
                        {
                            $user_answer->score = 0;

                            for ($i = 0; $i < $count; $i++)
                            {
                                if ($answers[$i]['answer_corresp'] == $answer_numbers[$i])
                                {
                                    $user_answer->score += $answers[$i]['answer_score'];
                                }
                            }
                        }
                        else
                        {
                            $user_answer->score = 0;
                        }
                    }
                    $user_answer->answered = 1;
                    $user_answer->question_id = $question->id;
                    if (is_showed_question($_SESSION['test']['user_result_id'], $question->id))
                    {
                        edit_user_answer($user_answer);
                    }
                    else
                    {
                        add_user_answer($user_answer);
                    }
                    break;

            }

            $_SESSION['test']['score'][$question->id] = $user_answer->score;

            if (($test->is_response_on_right == 1) && ($correct_answer))
            {
                $alert = $test->text_of_right_message;
                if (!isset($_SESSION['correct_answer_message']))
                {
                    $_SESSION['correct_answer_message'] = '';
                }
                $_SESSION['correct_answer_message'] .= $alert.'<br>';
            }

            if (($test->is_response_on_wrong == 1) && (!$correct_answer))
            {
                $alert = $test->text_of_wrong_message;
                if (!isset($_SESSION['errorstext']))
                {
                    $_SESSION['errorstext'] = '';
                }
                $_SESSION['errorstext'] .= $alert.'<br>';

            }
            $on_right_explanation = ($test->is_response_on_right == 1) && $correct_answer;
            $on_wrong_explanation = ($test->is_response_on_wrong == 1) && (!$correct_answer);
            if (($test->is_show_explanation == 1) &&
                ($on_right_explanation || $on_wrong_explanation)
            )
            {
                $explanation = $question->explanation;
                $explanation = str_replace('\n', '<br>',
                    $explanation);

                if (!isset($_SESSION['correct_answer_message']))
                {
                    $_SESSION['correct_answer_message'] = '';
                }
                if ($correct_answer)
                {
                    $_SESSION['correct_answer_message'] .= $explanation.'<br>';
                }
                else
                {
                    if (!isset($_SESSION['errorstext']))
                    {
                        $_SESSION['errorstext'] = '';
                    }

                    $_SESSION['errorstext'].= $explanation.'<br>';
                }
            }


            $WEB_APP['correct_answer_message'] =
                isset($_SESSION['correct_answer_message']) ? $_SESSION['correct_answer_message'] : '';


            $WEB_APP['errorstext'] = isset($_SESSION['errorstext']) ? $_SESSION['errorstext'] : '';

            $_SESSION['test']['previous_question_id'] = $question->id;
            $_SESSION['test']['previous_question'] = $question->text_html;
            $_SESSION['test']['previous_answer'] = $answer_text;

            $_SESSION['test']['correct_answer'] = $correct_answer;


            $right_questions = get_right_questions(
                $_SESSION['test']['user_result_id']);
            $answered_questions = get_answered_questions(
                $_SESSION['test']['user_result_id']);
            $questions_count = count($_SESSION['test']['questions']);
            $percent_right = round($right_questions/$questions_count*100, $WEB_APP['settings']['admset_percprecision']);
            $test = get_test($_SESSION['test']['test_id']);
            $user_id = get_user_id($_SESSION['user_login']);


            $user_result                      = new user_result();
            $user_result->completed_questions = $answered_questions;
            $user_result->id                  = $_SESSION['test']['user_result_id'];
            $user_result->percent_right       = $percent_right;
            $user_result->results             = '';
            $user_result->righ_questions      = $right_questions;
            $user_result->score               = array_sum($_SESSION['test']['score']);
            $user_result->test                = $test->id;
            $user_result->test_title          = $test->name;
            $user_result->time_begin          = gmdate('Y-m-d H:i:s', $_SESSION['test']['start_time']);
            $user_result->out_of_time         = ((($this->get_time_left() == NULL) && ($test->is_time_limit == 1)) ? 1 : 0);
            $user_result->completed           = ($user_result->out_of_time == 1) ? 1 : (($answered_questions == $questions_count) ? 1 : 0);
            $user_result->time_end            = (($user_result->completed || ($user_result->out_of_time == 1)) ? gmdate('Y-m-d H:i:s') : '0000-00-00 00:00:00');
            $user_result->total_questions     = $questions_count;
            $user_result->user                = $user_id;
            $user_result->test_data           = serialize($_SESSION['test']);

            edit_user_result($user_result);


            $_SESSION['test']['correct_answers'] = $right_questions;

            if ($test->is_next_when_right == 1)
            {
                if ($correct_answer)
                {
                    $_SESSION['test']['current_question']++;
                    if ($_SESSION['test']['current_question'] == count($_SESSION['test']['questions']))
                    {
                        $_SESSION['test']['all_questions'] = FALSE;
                        $_SESSION['test']['current_question'] = 0;
                    }
                    if (!$_SESSION['test']['all_questions'])
                    {
                        $cc = $_SESSION['test']['current_question'];
                        $qs = $_SESSION['test']['questions'][$cc];
                        $rs = $_SESSION['test']['results'][$qs];
                        while ((@$rs !== NULL) && ($_SESSION['test']['current_question'] < count($_SESSION['test']['questions'])))
                        {
                            if (!in_array(NULL, $_SESSION['test']['results'], TRUE)) {
                                $_SESSION['test']['current_question'] = count($_SESSION['test']['questions']);
                                break;
                            }

                            $_SESSION['test']['current_question']++;
                            if (in_array(NULL, $_SESSION['test']['results'], TRUE) && ($_SESSION['test']['current_question'] == count($_SESSION['test']['questions'])))
                            {
                                $_SESSION['test']['current_question'] = 0;
                            }
                            $cc = $_SESSION['test']['current_question'];
                            if (!isset($_SESSION['test']['questions'][$cc]))
                            {
                                break;
                            }
                            $qs = $_SESSION['test']['questions'][$cc];
                            $rs = $_SESSION['test']['results'][$qs];
                        }
                    }
                }
                else
                {
                    $_SESSION['errorstext'] = text('txt_insert_correct_answer').'<br>';
                }
            }
            else
            {
                if (($WEB_APP['settings']['tst_must_answer'] == 1) && ($_SESSION['test']['current_question'] >= 0) && (count($_POST) == 1))
                {
                    $_SESSION['errorstext'] = text('txt_insert_answer').'<br>';
                }
                else
                {
                    $_SESSION['test']['current_question']++;

                    if ($_SESSION['test']['current_question'] == count($_SESSION['test']['questions']))
                    {
                        $_SESSION['test']['all_questions'] = FALSE;
                        $_SESSION['test']['current_question'] = 0;
                    }
                    if (!$_SESSION['test']['all_questions'])
                    {
                        $cc = $_SESSION['test']['current_question'];
                        $qs = $_SESSION['test']['questions'][$cc];
                        $rs = $_SESSION['test']['results'][$qs];
                        while ((@$rs !== NULL) && ($_SESSION['test']['current_question'] < count($_SESSION['test']['questions'])))
                        {
                            if (!in_array(NULL, $_SESSION['test']['results'], TRUE))
                            {
                                $_SESSION['test']['current_question'] = count($_SESSION['test']['questions']);
                                break;
                            }
                            $_SESSION['test']['current_question']++;
                            if (in_array(NULL, $_SESSION['test']['results'], TRUE) && ($_SESSION['test']['current_question'] == count($_SESSION['test']['questions'])))
                            {
                                $_SESSION['test']['current_question'] = 0;
                            }

                            $cc = $_SESSION['test']['current_question'];
                            if (!isset($_SESSION['test']['questions'][$cc]))
                            {
                                break;
                            }
                            $qs = $_SESSION['test']['questions'][$cc];
                            $rs = $_SESSION['test']['results'][$qs];
                        }
                    }
                }
            }
        }


        if ($test->is_time_limit == 1)
        {
            $is_end_time = ($this->get_time_left() == NULL);
        }
        else
        {
            $is_end_time = FALSE;
        }

        if (($_SESSION['test']['current_question'] >= count($_SESSION['test']['questions'])) || $is_end_time)
        {
            if ($is_end_time)
            {
                $_SESSION['errorstext'] = text('txt_overtime').'<br>';
            }
            // Show rating.
            $test = get_test($_SESSION['test']['test_id']);

            $user_result = get_user_result(
                $_SESSION['test']['user_result_id']);

            if ($test->concl_type == 0)
            {
                $resume_text = get_resume_text_for_user_result_id($_SESSION['test']['user_result_id']);
                $conclusions_text = get_conclusions_text_for_user_result_id($_SESSION['test']['user_result_id']);
            }

            if ($test->concl_type == 1)
            {
                // Get max score.
                $all_questions = get_questions_for_test_id($test->id);
                $themes = get_themes_for_test_id($test->id);
                $max_scores = array();
                foreach($themes as $theme)
                {
                    $max_scores[$theme['theme_id']] = 0;
                }
                $max_score = 0;
                foreach($all_questions as $tmp_question)
                {
                    if (in_array($tmp_question['question_id'], $_SESSION['test']['questions']))
                    {
                        if ($test->type == 0)
                        {
                            $max_score += $tmp_question['question_weight'];
                            $max_scores[$tmp_question['question_theme_id']] += $tmp_question['question_weight'];
                        }
                        if ($test->type == 1)
                        {
                            switch($tmp_question['question_type'])
                            {
                                case 0:
                                    $max_score += $tmp_question['question_weight'];
                                    $max_scores[$tmp_question['question_theme_id']] += $tmp_question['question_weight'];
                                    break;

                                case 1:
                                    $answers = get_answers_for_question_id($tmp_question['question_id']);
                                    foreach($answers as $answer)
                                    {
                                        if ($answer['answer_right'] == 1)
                                        {
                                            $max_score += $tmp_question['question_weight'];
                                            $max_scores[$tmp_question['question_theme_id']] += $tmp_question['question_weight'];
                                        }
                                    }
                                    break;

                                case 2:
                                    $max_score += $tmp_question['question_weight'];
                                    $max_scores[$tmp_question['question_theme_id']] += $tmp_question['question_weight'];
                                    break;
                                case 3:
                                    $answers = get_answers_for_question_id($tmp_question['question_id']);
                                    $max_score += $tmp_question['question_weight']*count($answers);
                                    $max_scores[$tmp_question['question_theme_id']] += $tmp_question['question_weight']*count($answers);
                                    break;
                                case 4:
                                    $answers = get_answers_for_question_id($tmp_question['question_id']);
                                    $max_score += $tmp_question['question_weight']*count($answers)/2;
                                    $max_scores[$tmp_question['question_theme_id']] += $tmp_question['question_weight']*count($answers)/2;
                                    break;
                            }
                        }
                    }
                }

                $resume_text = get_resume_text_for_user_result_id_by_max_score($_SESSION['test']['user_result_id'], $max_score);
                $conclusions_text = get_conclusions_text_for_user_result_id_by_max_scores($_SESSION['test']['user_result_id'], $max_scores);

            }
            $right_questions = get_right_questions(
                $_SESSION['test']['user_result_id']);
            $answered_questions = get_answered_questions(
                $_SESSION['test']['user_result_id']);
            $questions_count = count($_SESSION['test']['questions']);

            $percent_right = round($right_questions/max(1, $questions_count)*100, $WEB_APP['settings']['admset_percprecision']);
            $test = get_test($_SESSION['test']['test_id']);
            $user_id = get_user_id(
                $_SESSION['user_login']);

            $user_result                      = new user_result();
            $user_result->completed           = ($answered_questions == $questions_count) ? 1 : 0;
            $user_result->completed_questions = $answered_questions;
            $user_result->id                  = $_SESSION['test']['user_result_id'];
            $user_result->percent_right       = $percent_right;
            $user_result->results             = $resume_text;
            $user_result->righ_questions      = $right_questions;
            $user_result->score               = array_sum($_SESSION['test']['score']);
            $user_result->test                = $test->id;
            $user_result->test_title          = $test->name;
            $user_result->time_begin          = gmdate('Y-m-d H:i:s', $_SESSION['test']['start_time']);
            $user_result->out_of_time         = ((($this->get_time_left() == NULL) && ($test->is_time_limit == 1)) ? 1 : 0);
            $user_result->completed           = ($user_result->out_of_time == 1) ? 1 : (($answered_questions == $questions_count) ? 1 : 0);
            $user_result->time_end            = (($user_result->completed || ($user_result->out_of_time == 1)) ? gmdate('Y-m-d H:i:s') : '0000-00-00 00:00:00');
            $user_result->total_questions     = $questions_count;
            $user_result->user                = $user_id;
            $user_result->test_data           = serialize($_SESSION['test']);

            edit_user_result($user_result);

            $user_result = get_user_result($_SESSION['test']['user_result_id']);
            $id = $_SESSION['test']['user_result_id'];

            foreach($conclusions_text as $user_result_theme)
            {
                foreach($_SESSION['test']['user_result_themes'] as $value)
                {
                    if ($value['title'] == $user_result_theme->theme)
                    {
                        edit_user_result_theme( $value['id'], $_SESSION['test']['user_result_id'],
                                        $user_result_theme->theme,
                                        $user_result_theme->result);
                    }
                }

            }

            $user_results = get_top_user_results_for_test_id($_SESSION['test']['test_id']);
            for ($i = 0; $i < count($user_results); $i++)
            {
                $user_results[$i]['id'] = $i + 1;
            }

            // Table titles.
            $columns = array();
            $columns[] = new column('id', '#');
            $columns[] = new column('user_name', text('txt_user_name'));
            $columns[] = new column('user_result_percent_right', text('txt_percentage_of_correct_answers'));

            unset($_SESSION['test']['test_id']);
            unset($_SESSION['test']['current_question']);
            unset($_SESSION['test']['previous_question']);
            unset($_SESSION['test']['previous_answer']);
            unset($_SESSION['test']['results']);

            $stat = array();

            if ($test->is_stat_total == 1)
            {
                $stat[] = array('name' => text('txt_total_questions'), 'value' => $user_result->total_questions);
            }

            $stat[] = array('name' => text('txt_answered'), 'value' => $user_result->completed_questions);

            if ($test->is_stat_rights == 1)
            {
                $stat[] = array('name' => text('txt_correct_answers'), 'value' => $user_result->righ_questions);
            }

            if ($WEB_APP['settings']['tst_showpercent'] == 1)
            {
                $stat[] = array('name' => text('txt_percentage_of_correct_answers'), 'value' => $user_result->percent_right);
            }
            $stat[] = array('name' => text('txt_testing_began'), 'value' => $user_result->time_begin);
            $stat[] = array('name' => text('txt_testing_finished'), 'value' => $user_result->time_end);

            if ($test->is_show_score == 1)
            {
                $stat[] = array('name' => text('txt_total_scores'), 'value' => $user_result->score);
            }

            $stat_columns = array();
            $stat_columns[] = new column('name', text('txt_param'));
            $stat_columns[] = new column('value', text('txt_value'));

            $user = get_user($user_id);

            // Send email
            $user_result->results = str_replace('<br>', '\r\n', $user_result->results);

            if ($WEB_APP['settings']['tst_resmailuser_send'] == 1)
            {
                $to = $user->mail;

                $message = str_replace('%TEST%', $user_result->test_title, $WEB_APP['settings']['tst_resmailuser_template']);
                $message = str_replace('%RESULTS%', $user_result->results, $message);
                $message = str_replace('%RIGHTCOUNT%', $user_result->righ_questions, $message);
                $message = str_replace('%SCORE%', $user_result->score, $message);
                $message = str_replace('%TIMEBEGIN%', $user_result->time_begin, $message);
                $message = str_replace('%TIMEEND%', $user_result->time_end, $message);
                $message = str_replace('%USERNAME%', $user->name, $message);
                $message = str_replace('%GROUP%', $user->group, $message);

                $subject = str_replace('%TEST%', $user_result->test_title, $WEB_APP['settings']['tst_resmailuser_subject']);
                $subject = str_replace('%RESULTS%', $user_result->results, $subject);
                $subject = str_replace('%RIGHTCOUNT%', $user_result->righ_questions, $subject);
                $subject = str_replace('%SCORE%', $user_result->score, $subject);
                $subject = str_replace('%TIMEBEGIN%', $user_result->time_begin, $subject);
                $subject = str_replace('%TIMEEND%', $user_result->time_end, $subject);
                $subject = str_replace('%USERNAME%', $user->name, $subject);
                $subject = str_replace('%GROUP%', $user->group, $subject);

                $headers = 'From: '.$WEB_APP['settings']['tst_resmailuser_from'].'\r\n' .
                'Reply-To: '.$WEB_APP['settings']['tst_resmailuser_from'].'\r\n' .
                'Content-Type: text/plain; charset=utf-8\r\n'.
                'X-Mailer: PHP/' . phpversion();

                mail($to, $subject, $message, $headers);
            }

            if ($WEB_APP['settings']['admset_resmail_send'] == 1)
            {
                $to = $WEB_APP['settings']['admset_resmail_to'];

                $message = str_replace('%TEST%', $user_result->test_title, $WEB_APP['settings']['admset_resmail_template']);
                $message = str_replace('%RESULTS%', $user_result->results, $message);
                $message = str_replace('%RIGHTCOUNT%', $user_result->righ_questions, $message);
                $message = str_replace('%SCORE%', $user_result->score, $message);
                $message = str_replace('%TIMEBEGIN%', $user_result->time_begin, $message);
                $message = str_replace('%TIMEEND%', $user_result->time_end, $message);
                $message = str_replace('%USERNAME%', $user->name, $message);
                $message = str_replace('%GROUP%', $user->group, $message);

                $subject = str_replace('%TEST%', $user_result->test_title, $WEB_APP['settings']['admset_resmail_subject']);
                $subject = str_replace('%RESULTS%', $user_result->results, $subject);
                $subject = str_replace('%RIGHTCOUNT%', $user_result->righ_questions, $subject);
                $subject = str_replace('%SCORE%', $user_result->score, $subject);
                $subject = str_replace('%TIMEBEGIN%', $user_result->time_begin, $subject);
                $subject = str_replace('%TIMEEND%', $user_result->time_end, $subject);
                $subject = str_replace('%USERNAME%', $user->name, $subject);
                $subject = str_replace('%GROUP%', $user->group, $subject);

                $headers = 'From: '.$WEB_APP['settings']['admset_resmail_from'].'\r\n' .
                'Reply-To: '.$WEB_APP['settings']['admset_resmail_from'].'\r\n' .
                'Content-Type: text/plain; charset=utf-8\r\n'.
                'X-Mailer: PHP/' . phpversion();

                mail($to, $subject, $message, $headers);
            }

            $user_result_themes = get_user_result_themes_for_user_result_id($_SESSION['test']['user_result_id']);

            $user_result_titles = array();
            $user_result_titles[] = array('name' => 'header', 'value' => text('txt_results'));
            $user_result_titles[] = array('name' => text('txt_result'), 'value' => $user_result->results);

            $tmp_themes = $this->get_show_in_results_array();
            foreach($user_result_themes as $user_result_theme)
            {
                if ($tmp_themes[$user_result_theme['user_result_themes_id']] == 1)
                {
                    $user_result_titles[] = array('name' => $user_result_theme['user_result_themes_theme_caption'], 'value' => $user_result_theme['user_result_themes_result']);
                }
            }
            $WEB_APP['user_result_themes'] = $user_result_titles;
            $WEB_APP['stat'] = $stat;
            $WEB_APP['stat_columns'] = $stat_columns;
            $WEB_APP['stat_rows_count'] = sizeof($stat);
            $WEB_APP['stat_columns_count'] = count($stat_columns);
            $WEB_APP['errorstext'] = isset($_SESSION['errorstext']) ? $_SESSION['errorstext'] : '';
            $WEB_APP['correct_answer_message'] =
                isset($_SESSION['correct_answer_message']) ? $_SESSION['correct_answer_message'] : '';
            unset($_SESSION['correct_answer_message']);
            $WEB_APP['tst_showstats'] = $WEB_APP['settings']['tst_showstats'] == 1;
            $WEB_APP['rows'] = $user_results;
            $WEB_APP['rows_count'] = count($user_results);
            $WEB_APP['editform'] = FALSE;
            $WEB_APP['columns'] = $columns;
            $WEB_APP['action'] = 'view';
            $WEB_APP['user_result'] = $user_result;
            $WEB_APP['resume_text'] = $resume_text.'<br>'.$conclusions_text;
            $WEB_APP['tst_showrating'] =
                ($WEB_APP['settings']['tst_showrating'] == 1) && ($WEB_APP['settings']['tst_ratingquantity'] > 0);
            $WEB_APP['columns_count'] = count($columns);
            $WEB_APP['test_name'] = $test->name;			
            $WEB_APP['title'] = text('txt_view_results');
            $WEB_APP['is_show_results_message'] = $test->is_show_results_message;
            $this->unset_test();
            $WEB_APP['view']->display('end_test.tpl',
                text('txt_view_results'));

            exit();
        }

        $question = get_question($_SESSION['test']['questions'][$_SESSION['test']['current_question']]);

        $hint_number = $question->hint;
   

            $hint = get_hint($_SESSION['test']['test_id'], $hint_number);			
			if (!empty($hint)) $WEB_APP['hint'] = $hint;
			else unset($WEB_APP['hint']);
     		

        if (!isset($_SESSION['test']['answers'][$question->id]))
        {
            $answers_array = array();
        }
        else
        {
            $answers_array = $_SESSION['test']['answers'][$question->id];
        }
        $answers = array();

        foreach($answers_array as $answer_index)
        {
            $answers[] = get_answer($answer_index);
        }
        $question_number = $_SESSION['test']['current_question'] + 1;
        $test = get_test($_SESSION['test']['test_id']);

        $WEB_APP['current_question'] = $_SESSION['test']['current_question']+1;

        $WEB_APP['stat_current'] = $test->is_stat_current == 1;
        $WEB_APP['tst_showquestionnumber'] = $WEB_APP['settings']['tst_showquestionnumber'] == 1;

        // Определяем тип мультимедийного файла
        $ext = strtolower(substr($question->picture_url, -3));
        // Изображение
        if (($ext == 'gif') || ($ext == 'jpg') || ($ext == 'png') || ($ext == 'bmp'))
            $mmtype = 'img';
        elseif (($ext == 'mid') || ($ext == 'midi') || ($ext == 'png') || ($ext == 'ra') ||
            ($ext == 'ram') || ($ext == 'mpg') || ($ext == 'mpeg') || ($ext == 'mp3') ||
            ($ext == 'mp2') || ($ext == 'wav') || ($ext == 'au') || ($ext == 'aif') || ($ext == 'aiff'))
        {
            if (($ext == 'mid') || ($ext == 'midi')) $mmtype = 'audio/x-midi';
            elseif (($ext == 'ra') || ($ext == 'ram')) $mmtype = 'audio/x-pr-realaudio';
            elseif (($ext == 'mpg') || ($ext == 'mpeg') || ($ext == 'mp3') || ($ext == 'mp2')) $mmtype = 'audio/x-mpeg';
            elseif ($ext == 'wav') $mmtype = 'audio/x-wav';
            elseif ($ext == 'au') $mmtype = 'audio/basic';
            elseif (($ext == 'aif') || ($ext == 'aiff')) $mmtype = 'audio/x-aiff';
        }
        $WEB_APP['mmtype'] = isset($mmtype) ? $mmtype : '';

        if ($test->is_stat_rights == 1)
        {
            $WEB_APP['correct_answers'] = $_SESSION['test']['correct_answers'];
        }
        $WEB_APP['is_back'] = ($test->is_back == 1);
        $WEB_APP['tst_showstats'] = ($WEB_APP['settings']['tst_showstats'] == 1);
        $WEB_APP['tst_allowstoskip'] = ($WEB_APP['settings']['tst_allowstoskip'] == 1) && ($WEB_APP['settings']['tst_must_answer'] == 0);
        if ($test->is_time_limit == 1)
        {
            $WEB_APP['time_left'] = $this->get_time_left();
        }
        else
        {
            $WEB_APP['time_left'] = text('txt_unrestrictedly');
        }
        $WEB_APP['question'] = $question;

        if ($test->is_stat_total == 1)
        {
            $WEB_APP['total_questions'] = count($_SESSION['test']['questions']);
        }

        $WEB_APP['show_time_left'] = $test->is_stat_time == 1;
        $WEB_APP['answers'] = $answers;
        if (isset($_SESSION['test']['results'][$question->id]))
        {
            $WEB_APP['results'] = $_SESSION['test']['results'][$question->id];
        }
        else
        {
            $WEB_APP['results'] = NULL;
        }
        $questions_count = count($_SESSION['test']['questions']);
        $right_questions = get_right_questions($_SESSION['test']['user_result_id']);

        $WEB_APP['answers_count'] = sizeof($answers);
        $WEB_APP['submit_title'] = text('txt_answer');
        $WEB_APP['media_storage'] = $test->media_storage;
		$WEB_APP['test_css'] = $test->css;

        $WEB_APP['previous_question'] =
            isset($_SESSION['test']['previous_question']) ? $_SESSION['test']['previous_question'] : '';
        $WEB_APP['previous_answer'] =
            isset($_SESSION['test']['previous_answer']) ? $_SESSION['test']['previous_answer'] : '';
        $WEB_APP['tst_showpercent'] = $WEB_APP['settings']['tst_showpercent'] == 1;
        $WEB_APP['percent_right'] = round($right_questions/$questions_count*100, $WEB_APP['settings']['admset_percprecision']);
        $WEB_APP['errorstext'] = isset($_SESSION['errorstext']) ? $_SESSION['errorstext'] : '';
        $WEB_APP['correct_answer_message'] =
            isset($_SESSION['correct_answer_message']) ? $_SESSION['correct_answer_message'] : '';
        $WEB_APP['correct_answer'] = isset($_SESSION['test']['correct_answer']) ? $_SESSION['test']['correct_answer'] : '';
        if (!$_SESSION['test']['all_questions'])
        {
            $title = text('txt_unanswered_question');
        }
        else
        {
            $title = text('txt_question');
        }
        if ($WEB_APP['settings']['tst_showquestionnumber'] == 1)
        {
            $question_number = $_SESSION['test']['current_question']+1;
            $title .= '&nbsp;'.$question_number;
        }

        $_SESSION['test']['user_result_time_id'] = 0;
        $this->time();
        $WEB_APP['scripts'][] = 'jquery.js';
        $WEB_APP['scripts'][] = 'jquery.timer.js';
        $WEB_APP['scripts'][] = 'jquery.hotkeys.min.js';
        $WEB_APP['scripts'][] = 'back_question.js';
        $WEB_APP['scripts'][] = 'skip_question.js';

        $WEB_APP['title'] = text('txt_question').' '.$question_number;
        $WEB_APP['view']->display('question.tpl', $WEB_APP['title']);
        unset($_SESSION['errorstext']);
        unset($_SESSION['correct_answer_message']);
    }

    public function time()
    {
        if ((!isset( $_SESSION['test']['user_result_id'])) ||
            (!isset($_SESSION['test']['current_question']))
           )
        {
            return;
        }

        $user_result_id = $_SESSION['test']['user_result_id'];
        $current_question = $_SESSION['test']['current_question'];

        if (!isset($_SESSION['test']['questions'][$current_question]))
        {
            return;
        }

        $question_id = $_SESSION['test']['questions'][$current_question];

        if (!isset($_SESSION['test']['user_result_time_id']))
        {
            return;
        }

        if ($_SESSION['test']['user_result_time_id'] == 0)
        {
            $_SESSION['test']['user_result_time_id'] = add_user_result_time($user_result_id, $question_id);
        }
        else
        {
            update_time_user_result_time($_SESSION['test']['user_result_time_id']);
        }
    }

    public function back_question()
    {
        if (isset($_SESSION['test']) &&
            is_array($_SESSION['test']) &&
            isset($_SESSION['test']['current_question']) &&
            isset($_SESSION['test']['test_id'])
        )
        {
            $test = get_test($_SESSION['test']['test_id']);

            if (isset($test->is_back) &&
                ($test->is_back == 1) &&
                ($_SESSION['test']['current_question'] > 0)
            )
            {
                $_SESSION['test']['current_question']--;
                echo '1';
            }
        }
        exit;
    }

    public function skip_question()
    {
        global $WEB_APP;

        if (isset($_SESSION['test']) &&
            is_array($_SESSION['test']) &&
            isset($_SESSION['test']['current_question']) &&
            isset($_SESSION['test']['test_id']) &&
            isset($WEB_APP['settings']) &&
            is_array($WEB_APP['settings']) &&
            isset($WEB_APP['settings']['tst_allowstoskip']) &&
            $WEB_APP['settings']['tst_allowstoskip']
        )
        {
            $_SESSION['test']['current_question']++;

            if ($_SESSION['test']['current_question'] == count($_SESSION['test']['questions']))
            {
                $_SESSION['test']['all_questions'] = FALSE;
                $_SESSION['test']['current_question'] = 0;
            }
            if (!$_SESSION['test']['all_questions'])
            {
                while (($_SESSION['test']['results'][$_SESSION['test']['questions'][$_SESSION['test']['current_question']]] !== NULL) &&
                       ($_SESSION['test']['current_question'] < count($_SESSION['test']['questions']))
                )
                {
                    $_SESSION['test']['current_question']++;
                    if (in_array(NULL, $_SESSION['test']['results'], TRUE) && ($_SESSION['test']['current_question'] == count($_SESSION['test']['questions'])))
                    {
                        $_SESSION['test']['current_question'] = 0;
                    }
                }
            }

            echo 1;
        }

        exit;
    }

    /**
     * Get theme_show_in_results params array from themes session info.
     *
     * @return array, keys - user result theme id, values - int (0, 1) is show result.
     */
    protected function get_show_in_results_array()
    {
        $themes = array();
        foreach($_SESSION['test']['user_result_themes'] as $theme)
        {
            $themes[$theme['id']] = $theme['show_in_results'];
        }

        return $themes;
    }
}
